<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Simple Super Mario</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #87CEEB;
            font-family: 'Arial', sans-serif;
        }
        canvas {
            border: 3px solid #333;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
        }
        #score {
            font-size: 24px;
            margin-bottom: 10px;
            color: #333;
        }
        #game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            display: none;
            z-index: 10;
            box-shadow: 0 0 20px rgba(0,0,0,0.5);
        }
        #restart-btn {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
        }
        #restart-btn:hover {
            background-color: #45a049;
        }
        /* 移动端控制按钮样式 */
        #mobile-controls {
            display: flex;
            /* justify-content: space-between; */
            justify-content: center;
            margin-top: 20px;
            width: 100%;
            max-width: 800px;
            padding: 0 10px;
        }
        .control-btn {
            width: 80px;
            height: 80px;
            margin-right: 30px;
            background-color: rgba(255, 255, 255, 0.8);
            border: 2px solid #333;
            border-radius: 50%;
            font-size: 28px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
        }
        .control-btn:active {
            background-color: rgba(200, 200, 200, 0.9);
        }
        #jump-btn{
            margin-left: auto;
            margin-right: 0;
        }
        @media (max-width: 768px) {
            canvas {
                width: 100%;
                max-width: 500px;
                height: auto;
            }
        }
    </style>
</head>
<body>
    <div id="score">分数: 0</div>
    <canvas id="gameCanvas" width="800" height="500"></canvas>
    
    <div id="mobile-controls">
        <div class="control-btn" id="left-btn">←</div>
        <div class="control-btn" id="right-btn">→</div>
        <div class="control-btn" id="jump-btn">↑</div>
    </div>
    
    <div id="game-over">
        <h2>游戏结束！</h2>
        <p>最终得分: <span id="final-score">0</span></p>
        <button id="restart-btn">重新开始</button>
    </div>
    
    <script>
        // Matter.js 模块
        const Engine = Matter.Engine;
        const Render = Matter.Render;
        const World = Matter.World;
        const Bodies = Matter.Bodies;
        const Body = Matter.Body;
        const Events = Matter.Events;
        const Runner = Matter.Runner;
        
        // 游戏变量
        let engine, runner;
        let mario;
        let platforms = [];
        let enemies = [];
        let coins = [];
        let score = 0;
        let isGameOver = false;
        
        // 获取画布和上下文
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const gameOverElement = document.getElementById('game-over');
        const finalScoreElement = document.getElementById('final-score');
        const restartButton = document.getElementById('restart-btn');
        
        // 游戏资源
        const marioColor = '#FF0000';
        const enemyColor = '#8B4513';
        const platformColor = '#44aa33';
        const coinColor = '#FFD700';
        const brickColor = '#B87333';
        
        // 初始化游戏
        function init() {
            // 创建物理引擎
            engine = Engine.create();
            engine.gravity.y = 1.2;
            
            // 创建运行器
            runner = Runner.create();
            Runner.run(runner, engine);
            
            // 创建马里奥
            mario = Bodies.rectangle(100, 400, 30, 40, {
                restitution: 0.1,
                friction: 0.05,
                density: 0.001,
                label: 'mario',
                render: { fillStyle: marioColor }
            });
            
            // 创建地面和平台
            createPlatforms();
            
            // 创建敌人
            createEnemies();
            
            // 创建金币
            createCoins();
            
            // 添加所有物体到世界
            World.add(engine.world, [mario, ...platforms, ...enemies, ...coins]);
            
            // 设置碰撞检测
            setupCollisions();
            
            // 启动游戏循环
            requestAnimationFrame(gameLoop);
        }
        
        // 创建平台
        function createPlatforms() {
            // 地面
            platforms.push(Bodies.rectangle(400, 490, 810, 20, { 
                isStatic: true,
                label: 'platform',
                render: { fillStyle: platformColor }
            }));
            
            // 平台
            platforms.push(Bodies.rectangle(300, 380, 150, 20, { 
                isStatic: true,
                label: 'platform',
                render: { fillStyle: platformColor }
            }));
            
            platforms.push(Bodies.rectangle(500, 300, 150, 20, { 
                isStatic: true,
                label: 'platform',
                render: { fillStyle: platformColor }
            }));
            
            platforms.push(Bodies.rectangle(700, 380, 150, 20, { 
                isStatic: true,
                label: 'platform',
                render: { fillStyle: platformColor }
            }));
            
            // 砖块
            platforms.push(Bodies.rectangle(400, 250, 50, 50, { 
                isStatic: true,
                label: 'brick',
                render: { fillStyle: brickColor }
            }));
        }
        
        // 创建敌人
        function createEnemies() {
            enemies.push(Bodies.rectangle(400, 450, 30, 30, {
                restitution: 0.2,
                friction: 0.05,
                label: 'enemy',
                render: { fillStyle: enemyColor }
            }));
            
            enemies.push(Bodies.rectangle(600, 450, 30, 30, {
                restitution: 0.2,
                friction: 0.05,
                label: 'enemy',
                render: { fillStyle: enemyColor }
            }));
        }
        
        // 创建金币
        function createCoins() {
            coins.push(Bodies.circle(300, 340, 10, {
                isStatic: true,
                isSensor: true,
                label: 'coin',
                render: { fillStyle: coinColor }
            }));
            
            coins.push(Bodies.circle(500, 260, 10, {
                isStatic: true,
                isSensor: true,
                label: 'coin',
                render: { fillStyle: coinColor }
            }));
            
            coins.push(Bodies.circle(700, 340, 10, {
                isStatic: true,
                isSensor: true,
                label: 'coin',
                render: { fillStyle: coinColor }
            }));
        }
        
        // 设置碰撞检测
        function setupCollisions() {
            Events.on(engine, 'collisionStart', function(event) {
                const pairs = event.pairs;
                
                for (let i = 0; i < pairs.length; i++) {
                    const pair = pairs[i];
                    
                    // 收集金币
                    if ((pair.bodyA.label === 'mario' && pair.bodyB.label === 'coin') ||
                        (pair.bodyA.label === 'coin' && pair.bodyB.label === 'mario')) {
                        const coin = pair.bodyA.label === 'coin' ? pair.bodyA : pair.bodyB;
                        World.remove(engine.world, coin);
                        coins = coins.filter(c => c !== coin);
                        score += 10;
                        scoreElement.textContent = `分数: ${score}`;
                    }
                    
                    // 碰到敌人
                    if ((pair.bodyA.label === 'mario' && pair.bodyB.label === 'enemy') ||
                        (pair.bodyA.label === 'enemy' && pair.bodyB.label === 'mario')) {
                        gameOver();
                    }
                    
                    // 破坏砖块
                    if ((pair.bodyA.label === 'mario' && pair.bodyB.label === 'brick') ||
                        (pair.bodyA.label === 'brick' && pair.bodyB.label === 'mario')) {
                        const brick = pair.bodyA.label === 'brick' ? pair.bodyA : pair.bodyB;
                        const marioBody = pair.bodyA.label === 'mario' ? pair.bodyA : pair.bodyB;
                        
                        // 只有从下方撞击才能破坏砖块
                        if (marioBody.position.y > brick.position.y) {
                            World.remove(engine.world, brick);
                            platforms = platforms.filter(p => p !== brick);
                            score += 5;
                            scoreElement.textContent = `分数: ${score}`;
                        }
                    }
                }
            });
        }
        
        // 游戏循环
        function gameLoop() {
            if (isGameOver) return;
            
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 移动敌人
            moveEnemies();
            
            // 绘制所有物体
            engine.world.bodies.forEach(body => {
                ctx.fillStyle = body.render.fillStyle || '#aaa';
                ctx.beginPath();
                
                if (body.label === 'mario') {
                    // 绘制马里奥（简单矩形）
                    ctx.fillRect(
                        body.position.x - 15,
                        body.position.y - 20,
                        30,
                        40
                    );
                } else if (body.label === 'enemy') {
                    // 绘制敌人（简单矩形）
                    ctx.fillRect(
                        body.position.x - 15,
                        body.position.y - 15,
                        30,
                        30
                    );
                } else if (body.label === 'coin') {
                    // 绘制金币（圆形）
                    ctx.arc(
                        body.position.x,
                        body.position.y,
                        10,
                        0,
                        Math.PI * 2
                    );
                    ctx.fill();
                } else {
                    // 绘制其他物体（平台、砖块等）
                    const width = body.bounds.max.x - body.bounds.min.x;
                    const height = body.bounds.max.y - body.bounds.min.y;
                    ctx.fillRect(
                        body.position.x - width/2,
                        body.position.y - height/2,
                        width,
                        height
                    );
                }
            });
            
            // 检查游戏结束条件
            if (mario.position.y > canvas.height) {
                gameOver();
                return;
            }
            
            requestAnimationFrame(gameLoop);
        }
        
        // 移动敌人
        function moveEnemies() {
            enemies.forEach(enemy => {
                // 简单的左右移动
                if (enemy.position.x > 700) {
                    Body.setVelocity(enemy, { x: -2, y: enemy.velocity.y });
                } else if (enemy.position.x < 100) {
                    Body.setVelocity(enemy, { x: 2, y: enemy.velocity.y });
                }
            });
        }
        
        // 游戏结束
        function gameOver() {
            isGameOver = true;
            finalScoreElement.textContent = score;
            gameOverElement.style.display = 'block';
        }
        
        // 重新开始游戏
        function restart() {
            // 清除世界中的所有物体
            World.clear(engine.world);
            
            // 重置游戏变量
            platforms = [];
            enemies = [];
            coins = [];
            score = 0;
            isGameOver = false;
            
            // 更新分数显示
            scoreElement.textContent = `分数: ${score}`;
            
            // 隐藏游戏结束界面
            gameOverElement.style.display = 'none';
            
            // 重新初始化游戏
            init();
        }
        
        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (isGameOver) return;
            
            const speed = 5;
            const jumpForce = -10;
            
            if (e.key === 'ArrowRight') {
                Body.setVelocity(mario, { x: speed, y: mario.velocity.y });
            } else if (e.key === 'ArrowLeft') {
                Body.setVelocity(mario, { x: -speed, y: mario.velocity.y });
            } else if (e.key === 'ArrowUp' || e.key === ' ') {
                jump();
            }
        });
        
        // 跳跃函数
        function jump() {
            if (isGameOver) return;
            
            const jumpForce = -10;
            
            // 改进的跳跃检测逻辑
            const canJump = engine.world.bodies.some(body => {
                if (body.label === 'platform' || body.label === 'brick') {
                    // 计算马里奥底部位置
                    const marioBottom = mario.position.y + 20; // 马里奥高度的一半
                    const platformTop = body.position.y - (body.bounds.max.y - body.bounds.min.y)/2;
                    
                    // 水平距离检查
                    const horizontalDistance = Math.abs(mario.position.x - body.position.x);
                    const platformHalfWidth = (body.bounds.max.x - body.bounds.min.x)/2;
                    
                    // 放宽判断条件，使跳跃更容易触发
                    return (marioBottom >= platformTop - 5) && // 马里奥在平台上方或接近平台
                           (marioBottom <= platformTop + 30) && // 不要太远
                           (horizontalDistance < platformHalfWidth + 30); // 水平方向上接近平台
                }
                return false;
            });
            
            if (canJump) {
                Body.setVelocity(mario, { x: mario.velocity.x, y: jumpForce });
            }
        }
        
        // 移动端控制
        const leftBtn = document.getElementById('left-btn');
        const rightBtn = document.getElementById('right-btn');
        const jumpBtn = document.getElementById('jump-btn');
        
        // 触摸事件 - 左移
        leftBtn.addEventListener('touchstart', (e) => {
            e.preventDefault();
            if (!isGameOver) {
                Body.setVelocity(mario, { x: -5, y: mario.velocity.y });
            }
        });
        
        // 触摸事件 - 右移
        rightBtn.addEventListener('touchstart', (e) => {
            e.preventDefault();
            if (!isGameOver) {
                Body.setVelocity(mario, { x: 5, y: mario.velocity.y });
            }
        });
        
        // 触摸事件 - 跳跃
        jumpBtn.addEventListener('touchstart', (e) => {
            e.preventDefault();
            jump();
        });
        
        // 鼠标点击事件（用于桌面端测试）
        leftBtn.addEventListener('mousedown', () => {
            if (!isGameOver) {
                Body.setVelocity(mario, { x: -5, y: mario.velocity.y });
            }
        });
        
        rightBtn.addEventListener('mousedown', () => {
            if (!isGameOver) {
                Body.setVelocity(mario, { x: 5, y: mario.velocity.y });
            }
        });
        
        jumpBtn.addEventListener('mousedown', () => {
            jump();
        });
        
        // 重新开始按钮事件
        restartButton.addEventListener('click', restart);
        
        // 启动游戏
        init();
    </script>
</body>
</html>